import { AdvContext, AdvVisitor } from "./adv";
import { Ast, createRootAst, uploadXml } from "./ast";


export class CloseAllVisitor extends AdvVisitor {
    visitView(node: Ast, ctx: AdvContext) {
        if (node.id.endsWith('clearAnimView')) {
            ctx.close = () => node.click()
            return;
        }
    }
    visitImageView(node: Ast, ctx: AdvContext){
        if (node.id.endsWith('clear_all_recents_image_button') && node.clickable) {
            ctx.close = () => node.click()
            return;
        }
    }
    visitFrameLayout(node: Ast, ctx: AdvContext) {
        if (node.id.endsWith(`recent_igmbutton_clear_all`)) {
            ctx.close = () => node.click()
            return;
        }
        node.children.map(c => c.visit(this, ctx))
    }
    visitButton(node: Ast, ctx: AdvContext){
        if(node.sid === `btn_clear` && node.clickable){
            ctx.close = () => node.click()
            return;
        }
    }
}

export function closeAllApplication() {
    const res = recents()
    if (res) {
        const visitor = new CloseAllVisitor()
        const ctx: AdvContext = {}
        let max: number = 10;
        while (!ctx.close && max > 0) {
            const root = createRootAst()
            visitor.visitNode(root, ctx)
            sleep(1000)
            max -=1;
        }
        if (ctx.close) {
            uploadXml(`dev`, `recents`)
            ctx.close()
            return true;
        }
        uploadXml(`dev`, `recents`)
        return false;
    }
}
